package MultiThreaded;
/**
 * 多线程：原子性/有序性/可序星
 * 共享锁：允许同一时刻，多个线程抢占一个资源
 * 排他锁：同一时刻，只允许一个线程
 * 加锁会将并行变成串行，可能会造成阻塞
 * 性能和安全要照顾到
 * 1.锁粒度优化
 * 2.无锁化编程-（乐观锁）
 * */
public class P1114 {

}
/**
 * 利用Synchronized锁
 * */
    class Foo {

        //控制变量
        private int flag=0;
        //定义Object类为锁
        private Object lock=new Object();

        public Foo() {
        }

        public void first(Runnable printFirst) throws InterruptedException {

            while(flag!=0){
                lock.wait();
            }

            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();

            flag=1;
            //唤醒其他线程
            lock.notifyAll();
        }

        public void second(Runnable printSecond) throws InterruptedException {
            while(flag!=1){
                lock.wait();
            }
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();

            flag=2;

            lock.notifyAll();
        }

        public void third(Runnable printThird) throws InterruptedException {

            while(flag!=0){
                lock.wait();
            }
            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();

            flag=3;

            lock.notifyAll();
        }
    }
